package com.qijian.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.SysDictData;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.system.domain.Organization;
import com.qijian.system.domain.vo.OrganizationQuery;
import com.qijian.system.service.IOrganizationService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.http.util.Asserts;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 组织Controller
 *
 * @author qijian
 * @date 2022-02-21
 */
@Api(tags = "组织")
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/organization")
public class OrganizationController extends BaseController {

    private final IOrganizationService organizationService;

    /**
     * 查询组织列表
     */
//    @PreAuthorize("@ss.hasPermi('business:organization:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrganizationQuery query, IPage<Organization> page) {
        QueryWrapper<Organization> queryWrapper = WhereEntityTool.invoke(query);
        queryWrapper.orderByAsc("number");
        return getDataTable(organizationService.page(Page.of(page.getCurrent(), page.getSize()),queryWrapper));
    }

    /**
     * 导出组织列表
     */
    @PreAuthorize("@ss.hasPermi('business:organization:export')")
    @Log(title = "组织" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(OrganizationQuery query, HttpServletResponse response) {
        QueryWrapper<Organization> queryWrapper = WhereEntityTool.invoke(query);
        queryWrapper.orderByDesc("create_time");

        List<Organization> list = organizationService.list(queryWrapper);
        Map<String, List<SysDictData>> stringListMap = organizationService.listDictByTypeValue();
        for (Organization organization :list){
            if(StringUtils.isNotEmpty(organization.getFOrgForm())&&stringListMap.containsKey(organization.getFOrgForm())){
                String fOrgForm = organization.getFOrgForm();
                List<SysDictData> sysDictData = stringListMap.get(fOrgForm);
                organization.setFOrgForm(stringListMap.get(organization.getFOrgForm()).get(0).getDictLabel());
            }
        }
        new ExcelUtil<>(Organization.class).exportExcel(response,list, "组织数据");
    }

    @PostMapping("/import")
    public AjaxResult importData(MultipartFile file) throws Exception {
        Asserts.check(file != null && !file.isEmpty(), "文件为空，无法导入");
        List<Organization> list = new ExcelUtil<>(Organization.class).importExcel(file.getInputStream());
        if(list.stream().anyMatch(x -> x.getNumber() == null || x.getFName() == null)){
            throw new Exception("组织编码或组织id必填，请检查数据！！！");
        }
        return AjaxResult.success(organizationService.importList(list));
    }

    @Log(title = "模版", businessType = BusinessType.EXPORT)
    @GetMapping("/template")
    public AjaxResult template() {
        Organization knifeCode = new Organization();
        return new ExcelUtil<>(Organization.class).exportExcel(CollUtil.newArrayList(knifeCode), "组织管理模版");
    }

    /**
     * 获取组织详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:organization:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(organizationService.getById(id));
    }

    /**
     * 新增组织
     */
    @PreAuthorize("@ss.hasPermi('business:organization:add')")
    @Log(title = "组织" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Organization organization) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("number", organization.getNumber());
        queryWrapper.eq("is_del", 0);
        List<Organization> list = organizationService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            throw new RuntimeException("编号已存在，请确认编号是否正确");
        }

        return toAjax(organizationService.save(organization));
    }

    /**
     * 修改组织
     */
    @PreAuthorize("@ss.hasPermi('business:organization:edit')")
    @Log(title = "组织" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Organization organization) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("number", organization.getNumber());
        queryWrapper.eq("is_del", 0);
        queryWrapper.ne("id", organization.getId());
        List<Organization> list = organizationService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            throw new RuntimeException("编号已存在，请确认编号是否正确");
        }
        return toAjax(organizationService.updateById(organization));
    }

    /**
     * 删除组织
     */
    @PreAuthorize("@ss.hasPermi('business:organization:remove')")
    @Log(title = "组织" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(organizationService.removeByIds(ids));
    }
}
